﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using SuppKids.Licensing.Common;
using SuppKids.Licensing.LicenseManager.Extensions;
using SuppKids.Licensing.LicenseManager.Resources;

namespace SuppKids.Licensing.LicenseManager
{
    public partial class MainWindow : BaseWindow
    {
        private readonly LicenseManagementService licenseManagementService;
        public MainWindow()
        {
            licenseManagementService = this.App.Container.Resolve<LicenseManagementService>();
            InitializeComponent();
            this.DataContext = new LicenseDTO();
        }

        public IEnumerable<MenuType> MenuTypes
        {
            get
            {
                return EnumExtensions.GetPossibleEnumValues<MenuType>();
            }
        }

        private void GenerateLicense_Click(object sender, RoutedEventArgs e)
        {
            var viewModel = (LicenseDTO)this.DataContext;
            if (string.IsNullOrWhiteSpace(viewModel.CMID))
            {
                MessageBox.Show(General.Message_CMIDisEmpty);
                return;
            }

            if (string.IsNullOrWhiteSpace(viewModel.ClientName))
            {
                MessageBox.Show(General.Message_ClientNameIsEmpty);
                return;
            }

            if (viewModel.ExpirationDate == default(DateTime))
            {
                MessageBox.Show(General.Message_ExpirationDateIsEmpty);
                return;
            }


            var saveFile = new SaveFileDialog
            {
                FileName = string.Format("SuppKids_Лицензия-{0}_период_{1}_до_{2:dd.MM.yyyy}.spkl", viewModel.ClientName, viewModel.MenuType.GetLocalizedEnumValue(), viewModel.ExpirationDate),
                DefaultExt = ".spkl",
                Filter = "SuppKids license files (.spkl)|*.spkl"
            };

            if (saveFile.ShowDialog() == true)
            {
                using (var stream = saveFile.OpenFile())
                {
                    var licenseString = this.licenseManagementService.GenerateAndSignXmlLicense(viewModel);
                    using (var writer = new StreamWriter(stream))
                    {
                        writer.Write(licenseString);
                    }
                }

                MessageBox.Show(General.Message_LicenseSaved);
            }
        }

        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            this.DataContext = new LicenseDTO();
        }
    }
}
